<script setup>
import { reactive, ref } from 'vue'
import { Lock, User } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

const loginForm = reactive({
  username: 'admin',
  password: '123456',
})

const loginRules = reactive({
  username: [
    {
      required: true,
      min: 3,
      max: 20,
      trigger: 'blur',
      message: 'username为3~20位',
    },
  ],
  password: [
    {
      required: true,
      min: 6,
      max: 20,
      trigger: 'change',
      message: '密码的长度应为6~20位',
    },
  ],
})

const redirect = ref('')
const loginFormRef = ref(null)

const handleLogin = async () => {
  const flag = await userStore.login(loginForm)
  if (flag) {
    await router.push({ path: redirect.value || '/' })
    ElMessage.success('Login successful')
  } else {
    ElMessage.error('Login failed: ' + userStore.err_msg)
  }
}
</script>

<template>
  <div class="login-container">
    <el-form
      ref="loginFormRef"
      :model="loginForm"
      :rules="loginRules"
      auto-complete="on"
      class="login-form"
      label-position="left"
    >
      <div class="title-container">
        <h1 class="title">Go网关后台管理</h1>
      </div>

      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          :prefix-icon="User"
          name="username"
          placeholder="Please input username"
          type="text"
        />
      </el-form-item>

      <el-form-item prop="password">
        <el-input v-model="loginForm.password" :prefix-icon="Lock" show-password type="password" />
      </el-form-item>

      <el-button style="width: 100%; margin: 0 auto 30px" type="primary" @click="handleLogin"
        >Login
      </el-button>

      <div class="tips">
        <span style="margin-right: 20px">username: admin</span>
        <span> password: 123456</span>
      </div>
    </el-form>
  </div>
</template>

<style lang="less" scoped>
.login-container {
  background-color: #2d3a4b;
  overflow: hidden;
  position: fixed;
  background-image: url('../assets/background.png');
  //display: flex;
  flex-direction: column; /* 垂直布局 */
  margin: 0;
  padding: 0;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;

  .login-form {
    position: relative;
    width: 520px;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15); // 添加视觉反馈 ：可考虑为登录表单添加轻微阴影提升层次感
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 36px;
      color: white;
      margin: 0 auto 40px auto;
      text-align: center;
      font-weight: bold;
      background-color: #66b1ff;
      padding: 10px;
      border-radius: 20px;
    }
  }
}
</style>
